package com.shaoyu.elasticsearch.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.thymeleaf.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @Description:
 * @Author: shaoyu1
 * @Date Create in 2018/6/25 16:17
 */
public class PropertiesUtil extends PropertyPlaceholderConfigurer {
    private static Map<String, Object> contextPropertys;

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
        contextPropertys = new HashMap<String, Object>();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String value = props.getProperty(keyStr);
            if (System.getProperties().containsKey(keyStr)) {
                value = System.getProperty(keyStr);
                props.setProperty(keyStr, value);
            }
            contextPropertys.put(keyStr, value);
        }
        super.processProperties(beanFactoryToProcess, props);
    }

    public static Object getValue(String name) {
        return contextPropertys.get(name);
    }

    public static String getValue(String name,String defaultValue) {
        String contextValue=(String)contextPropertys.get(name);
        return !StringUtils.isEmptyOrWhitespace(contextValue)?contextValue:defaultValue;
    }

    public static void showProperties() {
        Set <String> keys =  contextPropertys.keySet();
        for (String key:keys) {
            System.out.println(key+"="+contextPropertys.get(key));
        }
    }
}